package cn.longg.interceptor;

import cn.longg.entity.User;
import cn.longg.service.IUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否有记住我，是的话直接去主页，不是就放行
        Cookie[] cookies = request.getCookies();
        if(null != cookies){
            for (Cookie cookie : cookies) {
                if("rememberKey".equals(cookie.getName())){
                    String key = cookie.getValue();
                    String jsonStr = userService.getRemember(key);
                    if(null != jsonStr && !"".equals(jsonStr)){
                        User user = JSON.parseObject(jsonStr,User.class);
                        request.getSession().setAttribute("loginUser",user);
                        response.sendRedirect(request.getContextPath() + "/toHome");
                        return false;
                    }
                    break;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
